package com.zjmcollege.hotpot.controller;

import com.zjmcollege.hotpot.entity.Article;
import com.zjmcollege.hotpot.model.ArticleModel;
import com.zjmcollege.hotpot.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-11-07 21:11
 */
@Controller
@RequestMapping("/blog")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("/publish")
    public String createPage(Model model) {
        return "blog/publish";
    }

    @GetMapping("/publish/md")
    public String createPageMd(Model model) {
        return "blog/publish-md";
    }

    @GetMapping("/publish/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        Article article = articleService.findById(id);

        model.addAttribute("article", article);
        return "blog/edit";
    }
    @GetMapping
    public String blogList(Model model, @RequestParam(name = "page", defaultValue = "1")
            int page, @RequestParam(name = "page_size", defaultValue = "10")int pageSize) {
        Page<Article> articles = articleService.query(page, pageSize);
        model.addAttribute("articles", articles);
        return "blog/list";
    }

    /**
     * 创建博客
     * @param articleModel
     * @return
     */
    @PostMapping
    public String create(ArticleModel articleModel) {
        // TODO 跳转到成功页面上去，而不是list页面
        Article article = articleService.save(articleModel);
        if (article != null) {
            return "redirect:/blog";
        }

        return "redirect:/";
    }

    /**
     * 博客详情
     * @param id
     * @return
     */
    @GetMapping("/{id:\\d+}")
    public String detail(@PathVariable long id, Model model) {
        Article blog = articleService.findById(id);
        model.addAttribute("blog", blog);
        return "blog/detail";
    }
}
